package test.util;

import java.nio.charset.Charset;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.AuthSchemes;
import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import com.alibaba.fastjson.JSONObject;


public class HttpUtil {
	
	public static String httpGet(String url,JSONObject map) {
//		1、创建httpClient
		CloseableHttpClient client = HttpClients.createDefault();
//		2、封装请求参数
		List<BasicNameValuePair> list = new ArrayList<BasicNameValuePair>();
		for(String key : map.keySet()) {
			list.add(new BasicNameValuePair(key,map.getString(key)));
		}
		String result = null;
		try {
			//3、转化参数
			String params = EntityUtils.toString(new UrlEncodedFormEntity(list,Consts.UTF_8));
			System.out.println(params);
			//4、创建HttpGet请求 
			HttpGet httpGet = new HttpGet(url+"?"+params);
			CloseableHttpResponse response = client.execute(httpGet);
			
			//5、获取实体
			HttpEntity entity = response.getEntity();
			//将实体装成字符串
			result = EntityUtils.toString(entity);
			response.close();
		}catch (Exception e) {
			// TODO: handle exception
			throw new RuntimeException(e);
		}
		return result;
	}
	
	public static String httpPost(String url,String data,String token){  

		HttpClient httpclient =wrapClient(url);
        HttpPost post = new HttpPost(url);
        String result  = null;
        try {
        	System.out.println("请求\n"+data);
            StringEntity s = new StringEntity(data,Charset.forName("UTF-8"));
            s.setContentEncoding("UTF-8");
            s.setContentType("application/json;charset=utf-8");//发送json数据需要设置contentType
            post.setEntity(s);
            post.addHeader("accessToken", token);
            post.toString();
            HttpResponse res = httpclient.execute(post);
			/*
			 * if(res.getStatusLine().getStatusCode() == HttpStatus.SC_OK){ result =
			 * EntityUtils.toString(res.getEntity());// 返回json格式： }
			 */
            result = EntityUtils.toString(res.getEntity(),"UTF-8");// 返回json格式：
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return result;
          
    }   
	
	 /**
     * 获取 HttpClient
     * @param host
     * @param path
     * @return
     */
    private static HttpClient wrapClient(String url) {
        if (url != null && url.startsWith("https://")) {
            return sslClient();
        }
        HttpClient httpClient = HttpClientBuilder.create().build();
        return httpClient;
    }

	
	private static HttpClient sslClient() {
        try {
            // 在调用SSL之前需要重写验证方法，取消检测SSL
            X509TrustManager trustManager = new X509TrustManager() {
                @Override public X509Certificate[] getAcceptedIssuers() {
                    return null;
                }
                @Override public void checkClientTrusted(X509Certificate[] xcs, String str) {}
                @Override public void checkServerTrusted(X509Certificate[] xcs, String str) {}
            };
            SSLContext ctx = SSLContext.getInstance(SSLConnectionSocketFactory.TLS);
            ctx.init(null, new TrustManager[] { trustManager }, null);
            SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(ctx, NoopHostnameVerifier.INSTANCE);
            // 创建Registry
            RequestConfig requestConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD_STRICT)
                    .setExpectContinueEnabled(Boolean.TRUE).setTargetPreferredAuthSchemes(Arrays.asList(AuthSchemes.NTLM,AuthSchemes.DIGEST))
                    .setProxyPreferredAuthSchemes(Arrays.asList(AuthSchemes.BASIC)).build();
            Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
                    .register("http", PlainConnectionSocketFactory.INSTANCE)
                    .register("https",socketFactory).build();
            // 创建ConnectionManager，添加Connection配置信息
            PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
            CloseableHttpClient closeableHttpClient = HttpClients.custom().setConnectionManager(connectionManager)
                    .setDefaultRequestConfig(requestConfig).build();
            return closeableHttpClient;
        } catch (KeyManagementException ex) {
            throw new RuntimeException(ex);
        } catch (NoSuchAlgorithmException ex) {
            throw new RuntimeException(ex);
        }
    }

}
